﻿using System;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using System.Linq;
using System.Web.UI.WebControls;
using System.Text;   

namespace WordConversionManager.Layouts.WordConversionManager
{
    public static class Extensions
    {
        public static bool EventExists(this SPList List, string Assembly, string Class, SPEventReceiverType EventReceiverType)
        {
            if (List.EventReceivers.Cast<SPEventReceiverDefinition>().Any(eventReceiverDefinition =>
                (string.Compare(eventReceiverDefinition.Assembly, Assembly, true) == 0 &&
                 string.Compare(eventReceiverDefinition.Class, Class, true) == 0 &&
                 eventReceiverDefinition.Type == EventReceiverType)))
            {
                return true;
            }
            else
            {
                return false;
            }
        }
    }

    public partial class ConversionSettings : LayoutsPageBase
    {
        private const string _assemblyFullName = "WordConversionManager, Version=1.0.0.0, Culture=neutral, PublicKeyToken=71b6a3defef3871c";
        private const string _className = "WordConversionManager.WordConversionReceiver.WordConversionReceiver";

        private const string _listNotSelectedError = "Please select a list to configure settings.";

        private string[] SetOutputFormats
        {
            set
            {
                ListItem outputFileFormatListItem;

                foreach (string outputFormat in value)
                {
                    outputFileFormatListItem = outputFileFormatDropDown.Items.FindByValue(outputFormat);

                    if (outputFileFormatListItem != null)
                    {
                        outputFileFormatListItem.Selected = true;
                    }
                }
            }
        }

        private string GetOutputFormats
        {
            get 
            {
                StringBuilder outputFileFormats = new StringBuilder();

                foreach (ListItem outputFormatListItem in outputFileFormatDropDown.Items)
                {
                    if (outputFormatListItem.Selected)
                    {
                        if (outputFileFormats.Length != 0)
                        {
                            outputFileFormats.Append(";");
                        }

                        outputFileFormats.Append(outputFormatListItem.Value);
                    }
                }

                return outputFileFormats.ToString();
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                SPContext.Current.Web.AllowUnsafeUpdates = true;

                SPList list = this.CurrentList;

                if (list != null)
                {
                    sequenceTextBox.Text = WordConversionManagerSetttings.GetSequenceNumber(list);
                    SetOutputFormats = WordConversionManagerSetttings.GetOutputFileFormats(list);
                    SupportedInputFormats.Text = WordConversionManagerSetttings.GetSupportedFileFormats(list);

                    string destinationListId = WordConversionManagerSetttings.GetDestinationList(list);
                    OverwriteMethod overwrite = WordConversionManagerSetttings.GetOverwriteSetting(list);

                    OverwriteFileDropDown.SelectedValue = overwrite.ToString();

                    foreach (ListItem listItem in eventsCheckBoxList.Items)
                    {
                        SPEventReceiverType eventReceiverType = (SPEventReceiverType)Enum.Parse(typeof(SPEventReceiverType), listItem.Value);
                        if (list.EventExists(_assemblyFullName, _className, eventReceiverType))
                        {
                            listItem.Selected = true;
                        }
                    }

                    foreach (SPList destionationList in SPContext.Current.Web.Lists)
                    {
                        if (destionationList.BaseType == SPBaseType.DocumentLibrary)
                        {
                            DestionationListDropDown.Items.Add(new ListItem(destionationList.Title, destionationList.ID.ToString()));
                        }
                    }

                    Guid destinationListGuid;

                    if (Utilities.IsGuid(destinationListId, out destinationListGuid) && DestionationListDropDown.Items.FindByValue(destinationListId)!=null)
                    {
                        DestionationListDropDown.SelectedValue = destinationListId;
                    }
                }
                else
                {
                    ErrorMessageLiteral.Text = _listNotSelectedError;
                    SetSettingsButtonState(false);
                }
              
            }
        }

        private SPList CurrentList
        {
            get
            {
                string ListId = Request.QueryString["List"];
                Guid listGuid;

                if (ListId != "" && Utilities.IsGuid(ListId, out listGuid))
                {
                    return SPContext.Current.Web.Lists[listGuid];
                }
                else
                {
                    return null;
                }
            }
        }

        private void SetSettingsButtonState(bool State)
        {
            SaveSettingsButton.Enabled = State;
        }

        protected void SaveSettingsButton_OnClick(object sender, EventArgs e)
        {
            SPList currentList = this.CurrentList;

            if(currentList != null)
            {
                bool eventExists;

                foreach (ListItem listItem in eventsCheckBoxList.Items)
                {
                    SPEventReceiverType eventReceiverType = (SPEventReceiverType)Enum.Parse(typeof(SPEventReceiverType), listItem.Value);
                    eventExists = currentList.EventExists(_assemblyFullName, _className, eventReceiverType);

                    if (listItem.Selected && !eventExists)
                    {
                        SPEventReceiverDefinition recDef = currentList.EventReceivers.Add();
                        recDef.Name = listItem.Value;
                        recDef.Type = eventReceiverType;
                        recDef.Assembly = _assemblyFullName;
                        recDef.Class = _className;
                        recDef.SequenceNumber = Convert.ToInt32(sequenceTextBox.Text);

                        recDef.Update();
                    }
                    else if (!listItem.Selected && eventExists)
                    {
                        for (int i = currentList.EventReceivers.Count - 1; i >= 0; i--)
                        {
                            if (currentList.EventReceivers[i].Assembly == _assemblyFullName &&
                                currentList.EventReceivers[i].Class == _className &&
                                currentList.EventReceivers[i].Type == eventReceiverType)
                            {
                                currentList.EventReceivers[i].Delete();
                                currentList.EventReceivers[i].Update();
                            }
                        }
                    }
                }

                WordConversionManagerSetttings.SetPropertyValue(currentList, WordConversionManagerSetttings.SupportedInputFileFormats, SupportedInputFormats.Text);
                WordConversionManagerSetttings.SetPropertyValue(currentList, WordConversionManagerSetttings.OutputFileFormat, GetOutputFormats);
                WordConversionManagerSetttings.SetPropertyValue(currentList, WordConversionManagerSetttings.Overwrite, OverwriteFileDropDown.SelectedValue);
                WordConversionManagerSetttings.SetPropertyValue(currentList, WordConversionManagerSetttings.DestinationList, DestionationListDropDown.SelectedValue);
                WordConversionManagerSetttings.SetPropertyValue(currentList, WordConversionManagerSetttings.SequenceNumber, sequenceTextBox.Text);
            }

            Response.Redirect(string.Format("{0}/_layouts/listedit.aspx?List={1}", SPContext.Current.Web.Url, SPContext.Current.List.ID.ToString()));
        }
    }
}
